package com.example.vote.springboot_vote.controller;

import com.example.vote.springboot_vote.bean.User;
import com.example.vote.springboot_vote.services.UserServices;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.*;

//@Slf4j
@Controller
@RequestMapping("/api/view")
public class ViewController {
    @Autowired
    private UserServices userServicesImpl;


    private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(ViewController.class);

    @ResponseBody
    @RequestMapping("/login")
    public ModelAndView login() {
        log.info("视图跳转。。。");
        return new ModelAndView("login");
    }

    @ResponseBody
    @RequestMapping("/register")
    public ModelAndView register() {
        log.info("视图跳转。。。");
        return new ModelAndView("register");
    }

    @ResponseBody
    @RequestMapping("/index")
    public ModelAndView index() {
        log.info("视图跳转。。。");
        return new ModelAndView("index");
    }

    @ResponseBody
    @RequestMapping("/v_backround_admin")
    public ModelAndView backround_admin() {
        log.info("视图跳转。。。");
        return new ModelAndView("v_backround_admin");
    }

    @ResponseBody
    @RequestMapping("/v_users_table_test")
    public ModelAndView v_users_table_test() {
        log.info("视图跳转。。。");
        return new ModelAndView("v_users_table_test");
    }

    //是投票系统
    @ResponseBody
    @RequestMapping("/v_login")
    public ModelAndView v_login() {
        log.info("视图跳转。。。");
        return new ModelAndView("v_login");
    }

    @ResponseBody
    @RequestMapping("/v_upload")
    public ModelAndView v_upload() {
        log.info("视图跳转。。。");
        return new ModelAndView("v_upload");
    }
    @ResponseBody
    @RequestMapping("/v_upload1")
    public ModelAndView v_upload1() {
        log.info("视图跳转。。。");
        return new ModelAndView("v_upload1");
    }
    /**
     * 登录主方法
     *
     * @param user
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/v_check_login", method = RequestMethod.POST)
    public ModelAndView v_check_login(User user, HttpServletRequest request) {
        System.out.println(user.getName() + "," + user.getPwd());
        User fUser = userServicesImpl.getUser(user);
        ModelAndView mv = new ModelAndView();
        mv.addObject("date", new Date());
        if (null != fUser && fUser.getId() != null) {
            //success
            log.info("视图跳转。。。");
            mv.addObject("user", fUser);
            mv.setViewName("v_backround_admin");
            HttpSession session = request.getSession();//获取session并将userName存入session对象
            session.setAttribute("sessionUser", fUser);
        } else {
            //fail
            log.info("视图跳转。。。");
            mv.addObject("msg", "登录失败，账号或密码异常");
            mv.setViewName("fail");
        }
        return mv;
    }

    /**
     * 分页用户
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/vUserPage")
    public Map vUserPage(HttpServletRequest request) {
        Map pageInfo = new HashMap();
        String page = request.getParameter("page");
        String limit = request.getParameter("limit");
        String username = request.getParameter("username");
        String age = request.getParameter("age");

        pageInfo.put("page", Integer.valueOf(page));
        pageInfo.put("limit", Integer.valueOf(limit));
        List<User> list = userServicesImpl.getUserListByPage(pageInfo);
        list = userServicesImpl.getUserListByPageXml(pageInfo);
        Map res = new HashMap();
        res.put("code", 0);
        res.put("msg", "");
        res.put("count", 1000);
        res.put("data", list);
        return res;
    }


    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "vUploadFile", method = RequestMethod.POST)
    public String vUploadFile(@RequestParam("file") MultipartFile file) throws FileNotFoundException {
        String UPLOAD_FILE_PATH =ResourceUtils.getURL("classpath:static/").getPath()+File.separator+"v_uploadFile";
        if (!file.isEmpty()) {
            Map<String, String> resObj = new HashMap<>();
            try {
                File fTemp = new File(UPLOAD_FILE_PATH);
                if (!fTemp.exists()) {
                    fTemp.mkdirs();
                }
                File resFile = new File(UPLOAD_FILE_PATH, file.getOriginalFilename());
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(resFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                resObj.put("filePath",resFile.getName());
            } catch (IOException e) {
                resObj.put("msg", "error");
                resObj.put("code", "1");

//                return JSONObject.toJSONString(resObj);
            }
            resObj.put("msg", "ok");
            resObj.put("code", "0");
            return JSONObject.toJSONString(resObj);
        } else {
            return null;
        }
    }
    /**
     * 下载测试
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/vDownloadFile")
    @ResponseBody
    private void downloadFile(@RequestParam("fileName") String fileName,HttpServletResponse response) throws UnsupportedEncodingException, FileNotFoundException {
        String UPLOAD_FILE_PATH =ResourceUtils.getURL("classpath:static/").getPath()+File.separator+"v_uploadFile";
        File file = new File(UPLOAD_FILE_PATH+File.separator+fileName);
        if (file.exists()) {
            // 设置信息给客户端不解析
            String type = new MimetypesFileTypeMap().getContentType(fileName);
            // 设置contenttype，即告诉客户端所发送的数据属于什么类型
            response.setHeader("Content-type",type);
            // 设置编码
            fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
            // 设置扩展头，当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。
            response.setContentType("application/force-download");// 设置强制下载不打开            
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("下载成功");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        System.out.println("下载方法完毕");
    }
}
